<script setup>
import { useApi } from "../../composables/useApi.js";
import showTost from "@/components/toast/index.js";
import { storeToRefs } from "pinia";
import { useAppStore } from "../../store/app.js";

const appStore = useAppStore();

const { nationArr, sexArr } = storeToRefs(appStore);
import { reactive, ref } from "vue";
import StandardGradeDrawear from "@/pages/platform/components/standardGradeDrawear.vue";
import { router } from "@/plugins/1.router/index.js";
import * as XLSX from "xlsx";
import { getStudentList } from "@/api/student.js";
import { standardAddModify, standardDelete } from "@/api/standard.js";
import ModelHeader from "@/pages/platform/components/modelHeader.vue";
import UploadOhterImg from "@/components/uploadOhterImg.vue";
import {
  medalAddModify,
  medalDelete,
  medalRecordAddModify,
  medalRecordDelete,
} from "@/api/medal.js";
import MedalDrawear from "@/pages/platform/components/medalDrawear.vue";
//基本数据list
let list = ref([]);
let page = ref(1);
let limit = ref(20);
let total = ref(0); //总数
const selected = ref([]);
let queryFrom = ref({ page: 1, limit: 20 });

const headers = [
  {
    title: "奖章图标",
    key: "icon",
    width: "240px",
    align: "start",
  },
  {
    title: "奖章名称",
    width: "240px",
    align: "start",
    key: "title",
  },
  {
    title: "关联项目",
    width: "240px",
    align: "start",
    key: "scopeType",
  },
  {
    title: "分值",
    width: "240px",
    align: "start",
    key: "score",
  },

  {
    title: "奖章简介",
    width: "240px",
    align: "start",
    key: "info",
  },
  {
    title: "操作",
    align: "end",
    width: "240px",

    sortable: false,
    key: "options",
  },
];

const headersRecord = [
  {
    title: "奖章名称",
    key: "medalTitle",
    width: "240px",
    align: "start",
  },
  {
    title: "获奖学生",
    width: "240px",
    align: "start",
    key: "studentName",
  },
  {
    title: "颁奖教师",
    width: "240px",
    align: "start",
    key: "teacherName",
  },
  {
    title: "获奖时间",
    width: "240px",
    align: "start",
    key: "succTime",
  },

  {
    title: "评语",
    width: "240px",
    align: "start",
    key: "content",
  },
  {
    title: "操作",
    align: "end",
    width: "240px",
    sortable: false,
    key: "options",
  },
];

const examcourse_id = ref(null);
// todo 复制修改列表接口
const getList = async () => {
  const { data } = await useApi(
    tabsIndex.value == 0
      ? "/admin/Api.Medal/index"
      : "/admin/Api.Medalrecord/index"
  ).post({ ...queryFrom.value });
  total.value = data.value.data.total;
  list.value = data.value.data.data.map((item) => {
    return {
      ...item,
      id: tabsIndex.value === 1 ? item.medalrecord_id : item.medal_id,
    };
  });
  console.log("syz111", JSON.stringify(list.value));
};

const dialogFlag = ref(false);
// 头部表单回调
const onChange = (val) => {
  console.log("syz111", val);
  let data = JSON.parse(JSON.stringify(val));
  queryFrom.value = { ...queryFrom.value, ...data };
  getList();
};
const isConfirmDialogVisible = ref(false);
// 删除确认弹窗
const onHandleDelete = (val) => {
  console.log(val);
  if (tabsIndex.value == 0) {
    let ids = val.data.map((item) => item.medal_id).toString();
    medalDelete({ medal_id: ids }).then((res) => {
      showTost("删除成功", { duration: 3000, type: "success" });
      queryFrom.value.page = 1;
      isConfirmDialogVisible.value = false;
      if (val.type == "detail") {
        dialogFlag.value = false;
      }
      getList();
    });
  } else {
    let ids = val.data.map((item) => item.medalrecord_id).toString();
    medalRecordDelete({ medalrecord_id: ids }).then((res) => {
      showTost("删除成功", { duration: 3000, type: "success" });
      queryFrom.value.page = 1;
      isConfirmDialogVisible.value = false;
      if (val.type == "detail") {
        dialogFlag.value = false;
      }
      getList();
    });
  }
};
const selectedItems = ref([]);

// 确认弹窗文本
const confirmMsg = ref("");
const currentOptionData = ref({});

// 打开删除弹窗
const onHandleDialog = (type) => {
  if (type == "delete") {
    console.log(selectedItems);
    if (selectedItems.value.length == 0) return;
    let data = list.value.filter((item) =>
      selectedItems.value.find((val) => val == item.id)
    );
    console.log(data);
    currentOptionData.value = {
      data: data,
      type: "list",
    };
    confirmMsg.value = `确认删除${
      tabsIndex.value == 1
        ? data.map((item) => item.medalTitle).toString()
        : data.map((item) => item.title).toString()
    }的信息吗?`;
    isConfirmDialogVisible.value = true;
  } else if (type == "openSecondPage") {
    router.push("/platform/times-manage?type=2");
  } else {
    addDialogFlag.value = true;
  }
};
// 详情数据
const detailData = ref({});

// 去详情
const viewDetail = async (item) => {
  const { data } = await useApi(
    tabsIndex.value == 0 ? "/admin/Api.Medal/detail" : "/admin/Api.Medalrecord/detail"
  ).post({ medal_id: item.medal_id, medalrecord_id: item.medalrecord_id });
  console.log(data);
  detailData.value = data.value.data;
  dialogFlag.value = true;
};
// 添加教师弹窗falg
const addDialogFlag = ref(false);
const refVForm = ref();

// 下载模板
const downLoadTemplate = async () => {
  const { data } = await useApi("/admin/Base/downFile").post({ type: 5 });
  console.log(data.value);
  if (data.value.status == 200) {
    const link = document.createElement("a");
    link.href = data.value.data.fileUrl;
    link.download = data.value.data.fileName;
    link.target = "_blank"; // 可选，如果希望在新窗口中下载文件，请取消注释此行
    link.click();
  }
};
// 新增取消回调
const resetForm = () => {
  refVForm.value?.reset();
  addDialogFlag.value = false;
};

const valid = ref(false);
const form = reactive({
  title: "",
  medal_id: null,
  scopeType: "",
  score: "", //分值
  info: "", //章简介
  icon: "", //奖章图标
});

let totalScore = computed(() => {
  return (
    Number(form.languageScore) +
    Number(form.mathsScore) +
    Number(form.englishScore)
  );
});

const confirmAdd = async (args) => {
  console.log(totalScore.value);
  if (!valid.value) return;
  if (tabsIndex.value == 0) {
    medalAddModify({ ...form }).then((res) => {
      refVForm.value?.reset();
      addDialogFlag.value = false;
      showTost("新增成功", { duration: 3000, type: "success" });
      queryFrom.value.page = 1;
      getList();
    });
  } else {
    medalRecordAddModify({ ...form }).then((res) => {
      refVForm.value?.reset();
      addDialogFlag.value = false;
      showTost("新增成功", { duration: 3000, type: "success" });
      queryFrom.value.page = 1;
      getList();
    });
  }
};
let sexList = ref(["男", "女"]);
const onHandleEdit = () => {
  queryFrom.value.page = 1;
  getList();
};
// getList()
const required = (value, name) => !!value || `${name}为必填字段`;

const import_page = ref(1);
const import_limit = ref(10);
const import_percent = ref(0);
const loading = ref(false);

const partPost = async (tableData) => {
  let perdata = [];
  for (
    let i = (import_page.value - 1) * import_limit.value;
    i < import_page.value * import_limit.value;
    i++
  ) {
    if (tableData[i]) {
      perdata.push(tableData[i]);
    }
  }
  let total_page = Math.ceil(tableData.length / import_limit.value);
  import_percent.value = Math.ceil((import_page.value * 100) / total_page);
  loading.value = true;
  console.log(perdata);
  const { data } = await useApi("/admin/Api.Standardization/upload").post(
    JSON.stringify(perdata)
  );
  if (data.value.status == 200) {
    if (import_page.value <= total_page - 1) {
      import_page.value = import_page.value + 1;
      partPost(data);
    } else {
      // this.dialog.importDialogstatus = false;
      showTost("导入完成", { duration: 3000, type: "success" });
      loading.value = false;
    }
  }
};

const onChangePage = (val) => {
  queryFrom.value.page = val.page;
  queryFrom.value.limit = val.limit;
  getList();
};
const drawaerDelete = async (val) => {
  console.log(val);
  currentOptionData.value = {
    data: [val],
    type: "detail",
  };
  confirmMsg.value = `确认删除${val.title}的信息吗`;
  isConfirmDialogVisible.value = true;
};
const viewDetailClassStudent = (type, item) => {
  showTost("暂未开放");
  if (type == "class") {
  }
};
// 二级页面显示开关
const secondPageShowFlag = ref(false);
const onHandleSecondPage = () => {
  secondPageShowFlag.value = true;
};
const examTitle = ref("");
const changeId = (val) => {
  examcourse_id.value = val.id;
  examTitle.value = val.title;
  getList();
};
const httpRequest = (e) => {
  let file = e.file; // 文件信息
  if (!file) {
    return false;
  } else if (!/\.(xls|xlsx)$/.test(file.name.toLowerCase())) {
    // 格式根据自己需求定义
    this.$message.error("上传格式不正确，请上传xls或者xlsx格式");
    return false;
  }
  const fileReader = new FileReader();
  fileReader.onload = (ev) => {
    try {
      const data = ev.target.result;
      const workbook = XLSX.read(data, {
        // 以字符编码的方式解析
        type: "binary",
        cellDates: true,
      });
      // 取第一张表
      console.log(workbook);
      const exlname = workbook.SheetNames[0];
      const exl = XLSX.utils.sheet_to_json(workbook.Sheets[exlname]); // 生成json表格内容
      console.log(exl);
      partPost(exl);
      // 将 JSON 数据挂到 data 里
      let arr = [];
      exl.forEach((item) => {
        arr.push(item.name);
      });
      console.log(arr);
    } catch (e) {
      console.log("error");
      return false;
    }
  };
  fileReader.readAsBinaryString(file);
};

const onlyAllowNumbers = (event) => {
  const key = event.key;
  // 检查按键是否为数字或控制键（如 backspace）
  if (!/^\d$/.test(key) && event.key !== "Backspace" && event.key !== "Tab") {
    event.preventDefault();
  }
};
const filterInput = (key) => {
  // 仅保留数字
  form[key] = form[key].replace(/\D/g, "");
};

const projectList = ref(["德", "智", "体", "美", "劳"]);

const tabsIndex = ref(0);
const tabsChange = (index) => {
  tabsIndex.value = index;
  list.value = [];
  queryFrom.value.page = 1;
  getList();
};
/**  获取学生列表*/
const studentList = ref([]);
const getStudentListProp = async () => {
  getStudentList({ page: 1, limit: 9999 }).then((res) => {
    studentList.value = res.data.value.data;
    console.log(studentList.value);
  });
};
getStudentListProp();

/** 获取奖章列表不分页*/
const madelList = ref([]);
const getMadelList = async () => {
  const { data } = await useApi("/admin/Api.Medal/index").post({
    page: 1,
    limit: 9999,
  });
  madelList.value = data.value.data.data.map((item) => {
    return {
      ...item,
      id: item.medal_id,
    };
  });
};
getMadelList();

// 获取教师列表开始
const teacherList = ref([]);
const getTeacherList = async () => {
  const { data } = await useApi("/admin/Api.Teacher/indexList").post({});
  if (data.value.status == 200) {
    teacherList.value = data.value.data;
  }
};
getTeacherList();
// 获取教师列表结束
</script>

<template>
  <div class="content">
    <!--   Ought to 修改右侧抽屉-->
    <medal-drawear
      :tabs-index="tabsIndex"
      :madelList="madelList"
      :teacher-list="teacherList"
      @onHandleDelete="drawaerDelete"
      @onHandleEdit="onHandleEdit"
      :detailData="detailData"
      @update:isDrawerOpen="dialogFlag = $event"
      :is-drawer-open="dialogFlag"
      :student-list="studentList"
    ></medal-drawear>

    <ConfirmDialog
      :handleData="currentOptionData"
      v-model:isDialogVisible="isConfirmDialogVisible"
      @confirm="onHandleDelete"
      :confirm-msg="confirmMsg"
      :confirmation-question="confirmMsg"
      cancel-msg="Unsubscription Cancelled!!"
    />
    <!--    Ought to 修改顶部检索栏部分-->
    <!-- 头部 -->
    <model-header
      title="奖章列表"
      button-text="添加奖章"
      @tabsChange="tabsChange"
      @onChange="onChange"
      @changeId="changeId"
      @onHandle="onHandleDialog"
    />
    <VDataTable
      v-model="selectedItems"
      :headers="tabsIndex == 0 ? headers : headersRecord"
      :items-per-page="100"
      :items="list"
      item-key="id"
      show-select
      class="text-no-wrap"
    >
      <template #item.icon="{ item }">
        <div class="d-flex align-center" style="margin: 10px">
          <div class="d-flex flex-column">
            <img style="width: 64px" :src="item.icon" alt="" />
          </div>
        </div>
      </template>
      <template #item.averageScores1="{ item }">
        <div class="d-flex align-center">
          <div class="d-flex flex-column">
            {{ item.averageScores[0] }}
          </div>
        </div>
      </template>
      <template #item.averageScores2="{ item }">
        <div class="d-flex align-center">
          <div class="d-flex flex-column">
            {{ item.averageScores[1] }}
          </div>
        </div>
      </template>
      <template #item.averageScores3="{ item }">
        <div class="d-flex align-center">
          <div class="d-flex flex-column">
            {{ item.averageScores[2] }}
          </div>
        </div>
      </template>
      <template #item.averageScores4="{ item }">
        <div class="d-flex align-center">
          <div class="d-flex flex-column">
            {{ item.averageScores[3] }}
          </div>
        </div>
      </template>
      <template #item.averageScores5="{ item }">
        <div class="d-flex align-center">
          <div class="d-flex flex-column">
            {{ item.averageScores[4] }}
          </div>
        </div>
      </template>
      <template #item.options="{ item }">
        <div class="d-flex align-center options-right-display">
          <div class="d-flex flex-column ms-3 cursor-pointer">
            <i @click="viewDetail(item)" class="ri-menu-line"></i>
          </div>
        </div>
      </template>
    </VDataTable>
    <PaginationVue
      @onChange="onChangePage"
      :current-page="queryFrom.page"
      :page-size="queryFrom.limit"
      :total="total"
    />
    <!--    添加对话框-->
    <VDialog :persistent="true" max-width="600" :model-value="addDialogFlag">
      <div style="width: 600px" class="dialog-body">
        <AppDrawerHeaderSection
          title="添加奖章"
          @cancel="addDialogFlag = false"
        />
        <VDivider />
        <VCard>
          <PerfectScrollbar :options="{ wheelPropagation: false }" class="h-60">
            <VCardText>
              <VForm
                v-model="valid"
                ref="refVForm"
                @submit.prevent="confirmAdd"
              >
                <VRow v-if="tabsIndex == 0">
                  <VCol cols="6">
                    <VTextField
                      v-model="form.title"
                      label="奖章名称"
                      :rules="[(val) => required(val, '奖章名称')]"
                    >
                      <template v-slot:label>
                        <span>奖章名称</span>
                        <span style="color: red; margin-left: 4px">*</span>
                      </template>
                    </VTextField>
                  </VCol>
                  <VCol cols="6">
                    <VSelect
                      v-model="form.scopeType"
                      :items="projectList"
                      item-title="item"
                      item-value="item"
                      :rules="[(val) => required(val, '关联项目')]"
                      class="input-width-height"
                    >
                      <template v-slot:label>
                        <span>关联项目</span>
                        <span style="color: red; margin-left: 4px">*</span>
                      </template>
                    </VSelect>
                  </VCol>
                  <VCol cols="6">
                    <VTextField
                      v-model="form.score"
                      label="分值"
                      @keypress="onlyAllowNumbers"
                      @input="() => filterInput('score')"
                      :rules="[(val) => required(val, '分值')]"
                      placeholder="请输入分值"
                    >
                      <template v-slot:label>
                        <span>分值</span>
                        <span style="color: red; margin-left: 4px">*</span>
                      </template>
                    </VTextField>
                  </VCol>
                  <VCol cols="12">
                    <VTextarea
                      type="textarea"
                      v-model="form.info"
                      label="奖章简介"
                      placeholder="请输入奖章简介"
                    >
                    </VTextarea>
                  </VCol>
                  <VCol cols="12">
                    <div class="mb-1">奖章图标</div>
                    <upload-ohter-img
                      :limit="1"
                      :value="form.icon"
                      @input="
                        (val) => {
                          form.icon = val;
                        }
                      "
                    />
                  </VCol>
                  <VDivider style="margin-top: 20px" />
                  <VCol cols="12">
                    <div class="d-flex justify-end">
                      <VBtn type="submit" color="primary" class="me-4">
                        添加
                      </VBtn>
                    </div>
                  </VCol>
                </VRow>
                <VRow v-if="tabsIndex == 1">
                  <VCol cols="6">
                    <VSelect
                      v-model="form.medal_id"
                      :items="madelList"
                      item-title="title"
                      item-value="medal_id"
                      :rules="[(val) => required(val, '奖章名称')]"
                      class="input-width-height"
                    >
                      <template v-slot:label>
                        <span>奖章名称</span>
                        <span style="color: red; margin-left: 4px">*</span>
                      </template>
                    </VSelect>
                  </VCol>
                  <VCol cols="6">
                    <VSelect
                      v-model="form.student_id"
                      :items="studentList"
                      item-title="real_name"
                      item-value="student_id"
                      :rules="[(val) => required(val, '获奖学生')]"
                      class="input-width-height"
                    >
                      <template v-slot:label>
                        <span>获奖学生</span>
                        <span style="color: red; margin-left: 4px">*</span>
                      </template>
                    </VSelect>
                  </VCol>
                  <VCol cols="6">
                    <VSelect
                      v-model="form.teacher_id"
                      :items="teacherList"
                      item-title="real_name"
                      item-value="teacher_id"
                      placeholder="请选择评分老师"
                      label="评分老师"
                      class="input-width-height"
                    >
                      <template v-slot:label>
                        <span>评分老师</span>
                      </template>
                    </VSelect>
                  </VCol>
                  <VCol cols="6">
                    <AppDateTimePicker
                      class="input-width-height"
                      v-model="form.succTime"
                      label="获得时间"
                      placeholder="请选择获得时间"
                      :rules="[(val) => required(val, '获得时间')]"
                    >
                      <template v-slot:label>
                        <span>获得时间</span>
                        <span style="color: red; margin-left: 4px">*</span>
                      </template>
                    </AppDateTimePicker>
                  </VCol>
                  <VCol cols="12">
                    <VTextarea
                      type="textarea"
                      v-model="form.content"
                      label="评语"
                      placeholder="请输入评语"
                    >
                    </VTextarea>
                  </VCol>
                  <VDivider style="margin-top: 20px" />
                  <VCol cols="12">
                    <div class="d-flex justify-end">
                      <VBtn type="submit" color="primary" class="me-4">
                        添加
                      </VBtn>
                    </div>
                  </VCol>
                </VRow>
              </VForm>
            </VCardText>
          </PerfectScrollbar>
        </VCard>
      </div>
    </VDialog>
  </div>
</template>

<style lang="scss" scoped></style>
